<template>
    <div class="assignment-header">
        <button class="back-button" @click="$router.go(-1)"><img src="@/assets/svgs/left.svg" alt="Back" /></button>
        <div class="information">个人信息</div>
        <div class="user-info" @click="toggleDropdown">
            <img class="avatar" :src="userInfo?.avatarUrl" alt="User Avatar">
            <span class="username">{{ userInfo?.nick_name }}</span>
            <img class="dropdown-arrow" src="@/assets/svgs/downnarrow.svg" alt="Dropdown Arrow">
            <div v-if="dropdownVisible" class="dropdown-menu">
                <p @click="$router.push('/teacher/information')">个人信息</p>
                <p @click="$router.push('/login')">退出登录</p>
            </div>
        </div>
    </div>

    <div v-if="userInfo" class="infomation-div">
        <div class="information-img">
            <img :src="userInfo?.avatarUrl" style="width: 24lvw;height: 24lvw;border-radius: 3%;" alt="">
            <p class="title3" @click="updateavatarUrl">点击修改头像</p>
        </div>
        <div class="information-right">
            <div class="information-title">个人信息</div>
            <div class="information-item1">
                <div class="information-itemtext">&nbsp;&nbsp;账&nbsp;&nbsp;号&nbsp;：</div>
                <div class="information-item">{{ userInfo?.user_name }}</div>
            </div>
            <div class="information-item1">
                <div class="information-itemtext">&nbsp;&nbsp;昵&nbsp;&nbsp;称&nbsp;：</div>
                <div class="information-item">{{ userInfo?.nick_name }}</div>
            </div>
            <div class="information-item1">
                <div class="information-itemtext">&nbsp;&nbsp;性&nbsp;&nbsp;别&nbsp;：</div>
                <div class="information-item">{{ userInfo?.sex === '1' ? '男' : '0' ? '女' : '未知' }}</div>
            </div>
            <div class="information-item1">
                <div class="information-itemtext">&nbsp;&nbsp;邮&nbsp;&nbsp;箱&nbsp;：</div>
                <div class="information-item">{{ userInfo?.email }}</div>
            </div>
            <div class="information-item1">
                <div class="information-itemtext">&nbsp;&nbsp;电&nbsp;&nbsp;话&nbsp;：</div>
                <div class="information-item">{{ userInfo?.phonenumber }}</div>
            </div>
        </div>
        <el-button type="primary" size="default" class="recompose" @click="recompose">修改个人信息</el-button>
    </div>
    <div v-else>
        <p>加载中...</p>
    </div>
    <div v-if="compose" class="information-div2">
        <div class="information-title2">修改个人信息</div>
        <div class="information-item3">
            <div class="information-itemtext2">&nbsp;&nbsp;头&nbsp;&nbsp;像&nbsp;：</div>
            <div class="information-item4">
                <img :src="userInfo?.avatarUrl" style="width: 10lvh;height: 10lvh;border-radius: 3%;" alt="">
            </div>
        </div>
        <div class="information-item3">
            <div class="information-itemtext2">&nbsp;&nbsp;账&nbsp;&nbsp;号&nbsp;：</div>
            <div class="information-item2">{{ userInfo.user_name }}</div>
        </div>
        <div class="information-item3">
            <div class="information-itemtext2">&nbsp;&nbsp;昵&nbsp;&nbsp;称&nbsp;：</div>
            <div class="information-item4">
                <el-input v-model="tempUserInfo.nick_name" type="text" class="information-item4input" />
            </div>
        </div>
        <div class="information-item3">
            <div class="information-itemtext2">&nbsp;&nbsp;性&nbsp;&nbsp;别&nbsp;：</div>
            <el-radio-group v-model="tempUserInfo.sex" class="information-item4">
                <el-radio label="女" value="0"></el-radio>
                <el-radio label="男" value="1"></el-radio>
                <el-radio label="未知" value="2"></el-radio>
            </el-radio-group>
        </div>
        <div class="information-item3">
            <div class="information-itemtext2">&nbsp;&nbsp;邮&nbsp;&nbsp;箱&nbsp;：</div>
            <div class="information-item4">
                <el-input v-model="tempUserInfo.email" type="text" class="information-item4input" />
            </div>
        </div>
        <div class="information-item3">
            <div class="information-itemtext2">&nbsp;&nbsp;电&nbsp;&nbsp;话&nbsp;：</div>
            <div class="information-item4">
                <el-input v-model="tempUserInfo.phonenumber" type="text" class="information-item4input" />
            </div>
        </div>
        <div>
            <el-button type="primary" size="default" class="recompose1" @click="recomposeinformation">提交</el-button>
            <el-button size="default" class="recompose1" @click="recompose">取消</el-button>
        </div>
    </div>
    <div v-if="updateavatarUrlDiv" class="information-div3">
        <div class="information-title3">修改头像</div>
        <div class="information-item5">
            <img :src="userInfo?.avatarUrl" style="width: 40lvh;height: 40lvh;border-radius: 3%;" alt="">
        </div>
        <div class="upload-button">
            <label for="avatar-upload" class="button1">上传头像</label>
            <label @click="updateavatarUrl" class="button2">取消</label>
            <input type="file" id="avatar-upload" accept="image/*" @change="handleAvatarUpload" style="display: none;">
        </div>
    </div>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import { informationService, updateInformationService, updateAvatarService,uploadService } from '@/api/personnal-information';
import {ElMessage} from "element-plus";
// 控制台日志：初始化变量
console.log('初始化组件');

const dropdownVisible = ref(false);
const toggleDropdown = () => {
    dropdownVisible.value = !dropdownVisible.value;
    console.log('下拉菜单可见性切换:', dropdownVisible.value);
};

const userInfo = ref(null);

const fetchUserInfo = async () => {
    try {

        const result = await informationService();

        const userData = result.data; // 假设后端返回的数据结构是 { data: SysUser }
        userInfo.value = {
            userId: userData.userId,
            avatarUrl: userData.avatar,
            user_name: userData.userName,
            nick_name: userData.nickName
        };
    } catch (error) {
        console.error('获取用户信息失败:', result.message);
    }
};

onMounted(() => {
    console.log('组件已挂载，开始执行 fetchUserInfo');
    fetchUserInfo();
    // fetchAvatar();
});

const compose = ref(false);

const recompose = () => {
    compose.value = !compose.value;
    tempUserInfo.value = { ...userInfo.value };
};
// 临时用户信息，用于修改过程中保存修改后的值
const tempUserInfo = ref({
    nick_name: '',
    sex: '',
    email: '',
    phonenumber: ''
})
// 提交修改后的用户信息
const recomposeinformation = async () => {
    try {
        // 调用更新用户信息的API
        const params = {
            userName: userInfo.value.user_name,
            nickName: tempUserInfo.value.nick_name,
            sex: tempUserInfo.value.sex,
            email: tempUserInfo.value.email,
            phonenumber: tempUserInfo.value.phonenumber
        };

        await updateInformationService(params);

        // 更新显示数据
        userInfo.value.nick_name = params.nickName;
        userInfo.value.sex = params.sex;
        userInfo.value.email = params.email;
        userInfo.value.phonenumber = params.phonenumber;
        compose.value = false;
        // 提示用户更新成功
        ElMessage.success('用户信息更新成功');
    } catch (error) {
        console.error('用户信息更新失败:', error);
        // 提示用户更新失败
        ElMessage.error('用户信息更新失败，请重试');
    }
};


//修改头像逻辑
const updateavatarUrlDiv = ref(false);


// 切换上传头像弹窗的显示状态
const updateavatarUrl = () => {
  updateavatarUrlDiv.value = !updateavatarUrlDiv.value;
};

// 处理头像上传
const handleAvatarUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) {
    ElMessage.warning('请选择文件');
    return;
  }

  const formData = new FormData();
  formData.append('file', file); // 确保字段名与后端一致

  try {
    // 上传文件到服务器
    const uploadResponse = await uploadService(formData);
    userInfo.value.avatarUrl = uploadResponse.data; // 更新为服务器返回的 URL

    // 提交新头像 URL 到后端
    await updateAvatarService(userInfo.value.avatarUrl);
    console.log('头像已更新为:', userInfo.value.avatarUrl);

    // 提示用户更新成功
    ElMessage.success('头像更新成功');
  } catch (error) {
    console.error('头像更新失败:', error);
    // 提示用户更新失败
    ElMessage.error('头像更新失败，请重试');
  } finally {
    updateavatarUrlDiv.value = false; // 关闭上传头像的弹窗
    event.target.value = ''; // 清空文件输入框
  }
};


</script>

<style scoped>
.assignment-header {
    display: flex;
    height: 7lvh;
    width: 99lvw;
    background-color: #13227A;
    color: white;
}

.back-button {
    background-color: transparent;
    width: 3%;
    color: white;
    cursor: pointer;
}

.information {
    margin-left: 42%;
    font-size: 28px;
    line-height: 7lvh;
    font-family: kaiti;
    color: rgb(243, 245, 254);
}

.user-info {
    position: relative;
    align-items: center;
    cursor: pointer;
    display: flex;
    margin-left: 38%;
    z-index: 999;
}

.avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 10px;
}

.dropdown-arrow {
    width: 16px;
    height: 16px;
    margin-left: 5px;
}

.username {
    font-size: 16px;
}

.dropdown-menu {
    position: absolute;
    top: 100%;
    right: 0;
    background-color: white;
    color: black;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 10px;
    z-index: 1000;
}

.dropdown-menu :hover {
    background-color: #f0f0f0;
    color: brown;
}

.infomation-div {
    margin-left: 18%;
    margin-top: 10lvh;
    width: 62lvw;
    height: 72lvh;
    box-shadow: 2px 2px 4px rgba(112, 112, 112, 0.8);
    z-index: 1;
}

.information-img {
    margin-top: 5%;
    margin-left: 5%;
    float: left;
    width: 24lvw;
    height: 60lvh;
}

.title3 {
    margin-left: 30%;
    margin-top: 4%;
    font-size: 18px;
    text-decoration: underline;
}

.title3:hover {
    color: #0593ff;
}

.information-right {
    float: left;
    display: flex;
    flex-direction: column;
    width: 33lvw;
    height: 65lvh;
}

.information-title {
    float: left;
    font-size: 34px;
    margin-top: 5%;
    width: 20lvw;
    height: 5lvh;
    font-family: kaiti;
    font-weight: 500px;
    text-align: center;
}

.information-item1 {
    float: left;
    margin-top: 1%;
    width: 25lvw;
    height: 10lvh;
}

.information-itemtext {
    float: left;
    width: 10lvw;
    height: 10lvh;
    font-size: 28px;
    line-height: 10lvh;
    font-family: kaiti;
    color: rgb(90, 90, 90);
}

.information-item {
    float: left;
    margin-left: 2lvw;
    width: 13lvw;
    height: 10lvh;
    font-size: 28px;
    line-height: 10lvh;
    font-family: kaiti;
    color: rgb(28, 28, 28);
}


.recompose {
    float: left;
    margin-left: 40%;
}

.information-div2 {
    position: fixed;
    left: 29lvw;
    top: 10lvh;
    width: 35lvw;
    height: 75lvh;
    background-color: rgb(253, 253, 253);
    box-shadow: 2px 2px 4px rgba(151, 151, 151, 0.8);
    z-index: 2;
}

.information-title2 {
    float: left;
    font-size: 34px;
    font-family: kaiti;
    width: 35lvw;
    margin-top: 3%;
    text-align: center;
}

.information-itemtext2 {
    margin-left: 3lvw;
    float: left;
    width: 10lvw;
    height: 10lvh;
    font-size: 28px;
    line-height: 10lvh;
    font-family: kaiti;
    color: rgb(90, 90, 90);
}

.information-item2 {
    float: left;
    margin-left: 2lvw;
    width: 17lvw;
    height: 10lvh;
    font-size: 28px;
    line-height: 10lvh;
    font-family: kaiti;
    color: rgb(28, 28, 28);
}

.information-item1 {
    float: left;
    margin-top: 1%;
    width: 35lvw;
    height: 10lvh;
}

.information-item4 {
    float: left;
    margin-left: 2lvw;
    width: 17lvw;
    height: 10lvh;
    font-family: kaiti;
    color: rgb(28, 28, 28);
}

.information-item4input {
    width: 17lvw;
    margin-top: 2lvh;
    height: 6lvh;
    color: rgb(28, 28, 28);
}

.recompose1 {
    margin-left: 9lvw;
}

.information-div3 {
    position: fixed;
    left: 29lvw;
    top: 20lvh;
    width: 35lvw;
    height: 65lvh;
    background-color: rgb(248, 248, 248);
    box-shadow: 2px 2px 4px rgba(151, 151, 151, 0.8);
    z-index: 3;
}

.information-title3 {
    float: left;
    font-size: 34px;
    font-family: kaiti;
    width: 35lvw;
    margin-top: 4lvh;
    text-align: center;
}

.information-item5 {
    float: left;
    padding-left: 7lvw;
    margin-top: 2lvh;
    width: 35lvw;
    height: 40lvh;
}

.upload-button .button1 {
    display: inline-block;
    margin-left: 10lvw;
    margin-top: 4lvh;
    padding: 8px 16px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.upload-button .button1:hover {
    background-color: #0056b3;
}

.upload-button .button2 {
    display: inline-block;
    margin-left: 4lvw;
    margin-top: 4lvh;
    padding: 8px 16px;
    background-color: #ff5100;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.upload-button .button2:hover {
    background-color: #eabd92;
}
</style>
